<template>
  <u-comment :config="config" upload  @submit="submit" @like="like" relative-time>
    <!-- <template>导航栏卡槽</template> -->
    <!-- <template #info>用户信息卡槽</template> -->
    <!-- <template #card>用户信息卡片卡槽</template> -->
    <!-- <template #opearte>操作栏卡槽</template> -->
    <u-comment-nav v-model="latest" @sorted="sorted"></u-comment-nav>
  </u-comment>
</template>

<script setup>
// 下载表情包资源emoji.zip [emoji.zip下载](https://gitee.com/undraw/undraw-ui/releases/tag/v0.0.0)
// static文件放在public下,引入emoji.ts文件可以移动assets下引入,也可以自定义到指定位置
import emoji from '@/assets/js/emoji'
import { reactive,watch,onMounted,ref,defineEmits } from 'vue'
import { UToast, createObjectURL } from 'undraw-ui'
import { parseTime } from '@/utils/ruoyi'
import { getStudent } from '@/api/forum/student'
import { listReviewForPostId } from '@/api/forum/review'
import { isLike,getLikeListForUserPost } from '@/api/forum/reviewUpvote'
import { addReview } from '@/api/forum/review'
import { ElNotification } from 'element-plus'
import useUserStore from "@/store/modules/user"
import {fileUploads} from '@/api/forum/upload'
import {updatePost} from '@/api/forum/post'
import { ElMessage } from 'element-plus';
const props =defineProps({
  // 多种可能的类型 [String, Number]
  postInf: {
    type: Object,
    required: true
  },
  // // 必传，且为 String 类型
  isPostId: {
    type: Boolean,
    required: true
  },
})
watch(
  ()=>props.isPostId,
  () => {
    // console.log("开始请求评论数据。",props.isPostId,props.postInf);
    if(props.isPostId){
      // console.log("验证通过可以请求评论数据。")
      setTimeout(()=>{
        getStudentInf(props.postInf.userId);
        getPostReviewInf(props.postInf.id);
        getUserLikeList(useUserStore().id, props.postInf.id);
      },1000);
    }
  },
  { immediate: true }
)
const config = reactive({
  user: {
    id: useUserStore().id,
    username: useUserStore().nickName,
    avatar: useUserStore().avatar,
    // 评论id数组 建议:存储方式用户uid和评论id组成关系,根据用户uid来获取对应点赞评论id,然后加入到数组中返回
    likeIds: []
  },
  emoji: emoji,
  comments: [],
  total: 10,
  showLevel: false,
  showHomeLine: false
})
const postStudent = reactive({
  studentId: null,
  nickName: '',
  schoolId: null,
  collegeId: null,
})
const latest = ref(true);
//排序
const sorted = (latest) => {
  //true 最新 false 最热
  if(latest){
    //对评论进行排序根据点赞数量降序排序
    for(var i=0;i<config.comments.length; i++){
      for(var x=0;x<config.comments.length-1-i;x++){
        if(new Date(config.comments[config.comments.length-x-2].createTime).getTime() < new Date(config.comments[config.comments.length-x-1].createTime).getTime()){
          var tempReview = config.comments[config.comments.length-x-1];
          config.comments[config.comments.length-x-1] = config.comments[config.comments.length-x-2];
          config.comments[config.comments.length-x-2] = tempReview;
        }
      }
    }
    //记录当前用户在帖子上评论的数量
    var userSelfReviewSize = 0;
    //对评论数组进行当前用户评论置顶
    for(var i=0;i<config.comments.length;i++){
      var tempReview = config.comments[i];
      if(tempReview.uid == config.user.id){
        for(var x=0;x<i;x++){
          var tempReview = config.comments[i-x];
          config.comments[i-x] = config.comments[i-x-1];
          config.comments[i-x-1] = tempReview;
        }
        userSelfReviewSize++;
      }
    }
    //对置顶的评论进行点赞数量降序排序
    for(var i=0;i<userSelfReviewSize; i++){
      for(var x=0;x<userSelfReviewSize-1-i;x++){
        if(new Date(config.comments[userSelfReviewSize-x-2].createTime).getTime() < new Date(config.comments[userSelfReviewSize-x-1].createTime).getTime()){
          var tempReview = config.comments[userSelfReviewSize-x-1];
          config.comments[userSelfReviewSize-x-1] = config.comments[userSelfReviewSize-x-2];
          config.comments[userSelfReviewSize-x-2] = tempReview;
        }
      }
    }
  }else{
    //对评论进行排序根据点赞数量降序排序
    for(var i=0;i<config.comments.length; i++){
      for(var x=0;x<config.comments.length-1-i;x++){
        if(config.comments[config.comments.length-x-2].likes < config.comments[config.comments.length-x-1].likes){
          var tempReview = config.comments[config.comments.length-x-1];
          config.comments[config.comments.length-x-1] = config.comments[config.comments.length-x-2];
          config.comments[config.comments.length-x-2] = tempReview;
        }
      }
    }
    //记录当前用户在帖子上评论的数量
    var userSelfReviewSize = 0;
    //对评论数组进行当前用户评论置顶
    for(var i=0;i<config.comments.length;i++){
      var tempReview = config.comments[i];
      if(tempReview.uid == config.user.id){
        for(var x=0;x<i;x++){
          var tempReview = config.comments[i-x];
          config.comments[i-x] = config.comments[i-x-1];
          config.comments[i-x-1] = tempReview;
        }
        userSelfReviewSize++;
      }
    }
    //对置顶的评论进行点赞数量降序排序
    for(var i=0;i<userSelfReviewSize; i++){
      for(var x=0;x<userSelfReviewSize-1-i;x++){
        if(config.comments[userSelfReviewSize-x-2].likes < config.comments[userSelfReviewSize-x-1].likes){
          var tempReview = config.comments[userSelfReviewSize-x-1];
          config.comments[userSelfReviewSize-x-1] = config.comments[userSelfReviewSize-x-2];
          config.comments[userSelfReviewSize-x-2] = tempReview;
        }
      }
    }
  }
}
let temp_id = 100

//父子组件传递信息方法
const emits = defineEmits(['updatePost'])
// 提交评论事件
const submit = ({ content, parentId, files, finish, reply }) => {
  let str = '提交评论:' + content + ';\t父id: ' + parentId + ';\t图片:' + files + ';\t被回复评论:'
  // console.log(str, reply)
  /**
   * 上传文件后端返回图片访问地址，格式以'||'为分割; 如:  '/static/img/program.gif||/static/img/normal.webp'
   */
  let contentImg = files.map(e => createObjectURL(e)).join('||')

  const comment = {
    id: String((temp_id += 1)),
    parentId: parentId,
    uid: config.user.id,
    // address: '来自江苏',
    content: content,
    likes: 0,
    // createTime: '1分钟前',
    createTime: parseTime(new Date().getTime()),
    contentImg: contentImg,
    user: {
      username: config.user.username,
      avatar: config.user.avatar,
      level: 6,
      // homeLink: `/${(temp_id += 1)}`
    },
    reply: null
  }
  setTimeout(() => {
    // console.log(comment)
    finish(comment)
  }, 200)
  console.log('files',files)
  var tempFiles = [];
  for(var i=0;i<files.length;i++){
    tempFiles.push(files[i]);
  }
  console.log('tempFiles',tempFiles)
  //图片上传后端
  if(files.length>0){
    let formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });
    fileUploads(formData).then(res=>{
      console.log("uploadImage")
      console.log(res.fileNames)
      var imgNames = res.fileNames;
      var resultImgName = '';
      var imageNameList = imgNames.split(",");
      var b =imageNameList.map(img=>{
        return "/prod-api"+img;
      });
      for(var x=0;x<b.length;x++){
        if(x==b.length-1){
          resultImgName = resultImgName + b[x]
        }else{
          resultImgName = resultImgName + b[x]+'||';
        }
      }
      var data = {
        postId: props.postInf.id,
        userId: useUserStore().id,
        parentId: parentId,
        content: content,
        contentImg: resultImgName,
      }
      addReview(data).then(res=>{
        console.log("res",res)
        if(res.code == 555){
          ElMessage({
              showClose: true,
              message: res.msg,
              type: 'error',
          })
        }else if(res.code == 200){
          var data = {
            id: props.postInf.id,
            reviewNumber: props.postInf.reviewNumber+1
          }
          updatePost(data).then(res=>{
            emits('updatePost', 1);
            // console.log(res)
          });
          getPostReviewInf(props.postInf.id);
          UToast({ message: '评论成功!', type: 'info' })
        }
      }).catch(error=>{
        console.log("error",error)
        UToast({ message: '评论失败!', type: 'info' })
      })
    })
  }else{
    var data = {
      postId: props.postInf.id,
      userId: useUserStore().id,
      parentId: parentId,
      content: content,
      contentImg: '',
    }
    addReview(data).then(res=>{
      if(res.code == 555){
        ElMessage({
            showClose: true,
            message: res.msg,
            type: 'error',
        })
      }else if(res.code == 200){
        var data = {
          id: props.postInf.id,
          reviewNumber: props.postInf.reviewNumber+1
        }
        updatePost(data).then(res=>{
          emits('updatePost', 1);
          // console.log(res)
        });
        getPostReviewInf(props.postInf.id);
        UToast({ message: '评论成功!', type: 'info' })
      }
    }).catch(error=>{
      UToast({ message: '评论失败!', type: 'info' })
    })
  }
  // setTimeout(() => {
  //   // console.log(comment)
  //   finish(comment)
  // }, 200)
}



// 点赞按钮事件 将评论id返回后端判断是否点赞，然后在处理点赞状态
const like = (id, finish) => {
  var addData = {
    userId: useUserStore().id,
    reviewId: id
  }
  isLike(addData).then(res=>{
    ElNotification({
      message: res.msg ,
      type: 'success',
    })
  });
  setTimeout(() => {
    finish()
  }, 200)
}


const getStudentInf= (studentId)=>{
  getStudent(studentId).then(res=>{
      postStudent.studentId = studentId;
      postStudent.nickName = res.data.nickName;
      postStudent.schoolId = res.data.schoolId;
      postStudent.collegeId = res.data.collegeId;
      // console.log(postStudent)
    }
  );
};

const getPostReviewInf= (postId)=>{
  var param = {
    postId: postId
  }
  listReviewForPostId(param).then(res=>{
      config.comments = res.rows;
      //对评论进行排序
      sorted(true);
    }
  );
};

const getUserLikeList = (userId,postId)=>{
  var query = {
    userId: userId,
    postId: postId
  }
  // console.log(query)
  getLikeListForUserPost(query).then(res=>{
  // console.log(res)
    if(res.code == 200){
      config.user.likeIds = res.data;
    }
    // console.log(config.user.likeIds)
  });
}

onMounted(()=>{
  // console.log(config.user.id)
  //       console.log(useUserStore.id)
  //       getUserLikeList(useUserStore.id, props.postInf.id);
})

// config.comments = [
//   {
//     id: 1,
//     parentId: null,
//     uid: '1',
//     address: '来自'+"景德镇艺术职业大学",
//     content:
//       '缘生缘灭，缘起缘落，我在看别人的故事，别人何尝不是在看我的故事?别人在演绎人生，我又何尝不是在这场戏里?谁的眼神沧桑了谁?我的眼神，只是沧桑了自己[喝酒]',
//     likes: 2,
//     contentImg: 'https://gitee.com/undraw/undraw-ui/raw/master/public/docs/normal.webp||https://gitee.com/undraw/undraw-ui/raw/master/public/docs/normal.webp',
//     createTime: '1分钟前',
//     user: {
//       username: '落🤍尘',
//       // avatar: '',
//       // avatar: 'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
//       // level: 6,
//       // homeLink: '/1'
//     },
//     reply:{
//       total: 2,
//       list: [
//         {
//           id: 1,
//           parentId: 1,
//           uid: '1',
//           address: '来自'+"景德镇艺术职业大学",
//           content:
//             '缘生缘灭，缘起缘落，我在看别人的故事，别人何尝不是在看我的故事?别人在演绎人生，我又何尝不是在这场戏里?谁的眼神沧桑了谁?我的眼神，只是沧桑了自己[喝酒]',
//           likes: 2,
//           contentImg: 'https://gitee.com/undraw/undraw-ui/raw/master/public/docs/normal.webp||https://gitee.com/undraw/undraw-ui/raw/master/public/docs/normal.webp',
//           createTime: '1分钟前',
//           user: {
//             username: '落🤍尘',
//             // avatar: 'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
//             // level: 6,
//             // homeLink: '/1'
//           }
//         },
//         {
//           id: 3,
//           parentId: 2,
//           uid: '1',
//           address: '来自'+"景德镇艺术职业大学",
//           content:
//             '缘生缘灭，缘起缘落，我在看别人的故事，别人何尝不是在看我的故事?别人在演绎人生，我又何尝不是在这场戏里?谁的眼神沧桑了谁?我的眼神，只是沧桑了自己[喝酒]',
//           likes: 2,
//           contentImg: 'https://gitee.com/undraw/undraw-ui/raw/master/public/docs/normal.webp||https://gitee.com/undraw/undraw-ui/raw/master/public/docs/normal.webp',
//           createTime: '1分钟前',
//           user: {
//             username: '落🤍尘',
//             // avatar: 'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
//             // level: 6,
//             // homeLink: '/1'
//           }
//         }
//       ]
//     }
//   },
// ]
</script>